import React, { useEffect, useState } from "react";
import { IComponent } from "store/reducers/editor";
import { Button } from "antd";
import { EyeOutlined, EyeInvisibleOutlined } from "@ant-design/icons";
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd"
import "./index.scss";

interface ICompLayerSortProps {
    components: IComponent[];
    onChange: (components: IComponent[]) => void;
}

const CompLayerSort: React.FC<ICompLayerSortProps> = (props) => {
    const { components, onChange } = props;
    const [ compShow, setCompShow ] = useState<{[key: string]: boolean}>({});
    useEffect(() => {
      const compShowState = {};
      components.forEach(comp => {
        const display = Reflect.get(comp.props, "display")
        Reflect.set(compShowState, comp.id, display === "none" ? false : true)
      })
      setCompShow(compShowState);
    }, [components])
    const onDragEnd = (result: any) => {
      if (!result.destination) {
        return;
      }
      const list = Array.from(components);
      const [removed] = list.splice(result?.source?.index, 1);
      list.splice(result?.destination?.index, 0, removed);
      onChange(list);
    }
    const toggleLayerShow = (comp: IComponent) => {
      const { id } = comp;
      const curIndex = components.findIndex(item => item.id === id);
      if(curIndex !== -1){
        Reflect.set(components[curIndex]?.props, "display", compShow?.[id] ? "none" : "block");
        onChange([...components])
      }
    }
    return (<DragDropContext onDragEnd={onDragEnd}>
          <Droppable droppableId="droppable" direction="vertical">
            {(provided) => (
              <div
                {...provided.droppableProps}
                ref={provided.innerRef}
                className="droppable-item"
              >
                {components.map((comp, index) => (
                  <Draggable key={comp.id} draggableId={comp.id} index={index}>
                    {(provided, snapshot) => (
                      <div
                        ref={provided.innerRef}
                        {...provided.draggableProps}
                        {...provided.dragHandleProps}
                        className="drag-layer-wrapper"
                        style={{...provided.draggableProps.style}}
                      >
                        <div className="show-comp">
                          <Button onClick={() => toggleLayerShow(comp)}>{!compShow?.[comp.id] ? <EyeOutlined /> : <EyeInvisibleOutlined />}</Button>
                        </div>
                        <span className="layer-name">图层{comp.index}</span>
                      </div>
                    )}
                  </Draggable>
                ))}
                {provided.placeholder}
              </div>
            )}
          </Droppable>
      </DragDropContext>)
}

export default CompLayerSort;